package cn.ly.core.aio;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * Created with IntelliJ IDEA. User: twer Date: 5/2/12 Time: 8:37 PM To change
 * this template use File | Settings | File Templates.
 */

public class AFCDemo {
	static Thread current;

	public static void main(String[] args) throws IOException, InterruptedException, ExecutionException {
		/*if (args == null || args.length == 0) {
			System.out.println("Please input file path");
			return;
		}*/
		Path filePath = Paths.get("C:\\Documents and Settings\\liuyu\\桌面\\abc.txt");
		AsynchronousFileChannel afc = AsynchronousFileChannel.open(filePath);
		ByteBuffer byteBuffer = ByteBuffer.allocate(16 * 1024);
		// 使用FutureDemo时，请注释掉completionHandlerDemo，反之亦然
		//futureDemo(afc, byteBuffer);
		completionHandlerDemo(afc, byteBuffer);
	}

	private static void completionHandlerDemo(AsynchronousFileChannel afc, ByteBuffer byteBuffer) throws IOException {
		System.out.println(byteBuffer);
		current = Thread.currentThread();
		//aio的read方法是非阻塞的，如果是老的bio的read方法就是阻塞的
		afc.read(byteBuffer, 0, null, new CompletionHandler<Integer, Object>() {
			@Override
			public void completed(Integer result, Object attachment) {
				System.out.println("Bytes Read = " + result);
				current.interrupt();
			}

			@Override
			public void failed(Throwable exc, Object attachment) {
				current.interrupt();
			}
		});
		//不阻塞，先执行这个打印
		System.out.println("Waiting for completion...");
		try {
			//等待io线程写完毕，再继续往下执行
			current.join();
		} catch (InterruptedException e) {
		}
	
		System.out.println(byteBuffer);
		//转换模式
		byteBuffer.flip();
		
		byte[] bytes = new byte[66];
		bytes = byteBuffer.array();
		String str = new String(bytes);
		System.out.println("=========start=========");
		System.out.println(str);
		System.out.println("=========end==========");
		System.out.println("End");
		afc.close();
	}

	private static void futureDemo(AsynchronousFileChannel afc, ByteBuffer byteBuffer)
			throws InterruptedException, ExecutionException, IOException {
		//read方法是非阻塞的，继续向下执行
		Future<Integer> result = afc.read(byteBuffer, 0);
		//上面的io read方法不阻塞，执行这个while循环，循环判断期待的Future是否完成
		while (!result.isDone()) {
			System.out.println("Waiting file channel finished....");
			Thread.sleep(1);
		}
		System.out.println("Finished? = " + result.isDone());
		System.out.println("byteBuffer = " + result.get());
		System.out.println(byteBuffer);
		afc.close();
	}
}
